﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Zwms.Client.CommonUI;
using Zwms.Client.Helper;
using Zwms.Data.BusinessObjects;
using Zwms.Data.CommonObject;
using Zwms.Client.InfoSys;

namespace Zwms.Client.InWms
{
    public partial class ReceiveForm : BaseForm
    {
        #region 成员变量
        private string _sInPlanBillCode;
        private string _sInBillCode;
        private DateTime _dtnow = DateTime.Now;
        private string _sLastScanCode;
        private IList<BilInPlanBillDetail> _recieveList;
        #endregion

        #region 构造函数
        public ReceiveForm(string sPlanBillCode,string sBillCode)
        {
            InitializeComponent();
            _sInPlanBillCode = sPlanBillCode;
            _sInBillCode = sBillCode;
            InitBtnImage();
            InitControl();
        }

       
        #endregion

        #region 私有函数
        private void InitBtnImage()
        {
            this.btnClearSingle.Image = global::Zwms.Client.Properties.Resources.remove;
            this.btnClearAll.Image = global::Zwms.Client.Properties.Resources.cancel2;
            this.btnConfirm.Image = global::Zwms.Client.Properties.Resources.ok;
            this.btnCancel.Image = global::Zwms.Client.Properties.Resources.cancel;
        }
        private void InitControl()
        {
            LoadPlanRecieveList();
        }

        //载入待收货物列表
        private void LoadPlanRecieveList()
        {
            lsvPlanRecieve.Items.Clear();
            ServiceReferenceZwms.ServiceZwmsClient client
                = new ServiceReferenceZwms.ServiceZwmsClient();
           

            BilInPlanBillDetail queryRecord = new BilInPlanBillDetail();
            queryRecord.IBPlanCode = _sInPlanBillCode;
            PagerIndex pIndex = new PagerIndex(1, int.MaxValue);
            _recieveList = client.QueryInPlanBillDetailList(queryRecord, ref pIndex);

            foreach (BilInPlanBillDetail record in _recieveList)
            {
                ListViewItem lvItem = new ListViewItem(record.GoodsBarCode);
                lvItem.SubItems.Add(record.GoodsName);
                lvItem.SubItems.Add(record.SingleGoodsCode);
                lvItem.SubItems.Add(record.GoodsPackageQty.ToString());
                lvItem.SubItems.Add(record.GoodsPieceQty.ToString());
                lvItem.SubItems.Add(record.ReceiveGoodsPackageQty.ToString());
                lvItem.SubItems.Add(record.ReceiveGoodsPieceQty.ToString());

                //着色
                if ((record.ReceiveGoodsPackageQty == record.GoodsPackageQty)
                    && (record.ReceiveGoodsPieceQty == record.GoodsPieceQty))
                {
                    lvItem.BackColor = Color.Green;
                }
                else if ((record.ReceiveGoodsPackageQty > record.GoodsPackageQty)
                    || (record.ReceiveGoodsPieceQty > record.GoodsPieceQty))
                {
                    lvItem.BackColor = Color.Red;
                }
                else if ((record.ReceiveGoodsPackageQty <= record.GoodsPackageQty)
                    && (record.ReceiveGoodsPieceQty <= record.GoodsPieceQty))
                {
                    lvItem.BackColor = Color.Yellow;
                }
                
                lsvPlanRecieve.Items.Add(lvItem);
            }
        }

        //参数bIsScan表示是否为扫描结果
        private void RecieveGoods(string sGoodsCode,string sDate, int iPackageQty,int iPieceQty)
        {
            if (sGoodsCode == null)
            {
                return;
            }
            ServiceReferenceZwms.ServiceZwmsClient client
                 = new ServiceReferenceZwms.ServiceZwmsClient();
            bool bHave = false;

            if (sDate != "")
            {
                //整箱
                List<BilInPlanBillDetail> packageList = _recieveList.Where(c => c.GoodsBarCode == string.Format("{0}#{1}", sGoodsCode, sDate)).ToList();
                if (packageList.Count == 0)
                {
                    //计划之外
                }
                else if (packageList.Count == 1)
                {
                    bHave = true;
                    packageList[0].ReceiveGoodsPackageQty += iPackageQty;
                    packageList[0].ReceiveGoodsPieceQty += iPieceQty;
                    packageList[0].ReceiveGoodsQty = packageList[0].ReceiveGoodsPackageQty * packageList[0].GoodsSpec + packageList[0].ReceiveGoodsPieceQty;

                    if (!client.UpdateInPlanBillDetail(packageList[0]))
                    {
                        MessageBox.Show("更新出库计划明细信息失败！");
                        return;
                    }
                }
                else if (packageList.Count > 1)
                {
                    bHave = true;
                    for (int j = 0; j < packageList.Count; j++)
                    {
                        if (packageList[j].ReceiveGoodsPackageQty < packageList[j].GoodsPackageQty ||
                            packageList[j].ReceiveGoodsPieceQty < packageList[j].GoodsPieceQty)
                        {
                            if (iPackageQty < (packageList[j].GoodsPackageQty - packageList[j].ReceiveGoodsPackageQty))
                            {
                                packageList[j].ReceiveGoodsPackageQty += iPackageQty;
                                iPackageQty = 0;
                            }
                            else if (iPackageQty == (packageList[j].GoodsPackageQty - packageList[j].ReceiveGoodsPackageQty))
                            {
                                packageList[j].ReceiveGoodsPackageQty += iPackageQty;
                                iPackageQty = 0;
                            }
                            else if (iPackageQty > (packageList[j].GoodsPackageQty - packageList[j].ReceiveGoodsPackageQty))
                            {
                                iPackageQty = iPackageQty - (packageList[j].GoodsPackageQty - packageList[j].ReceiveGoodsPackageQty);
                                packageList[j].ReceiveGoodsPackageQty = packageList[j].GoodsPackageQty;
                            }

                            if (iPieceQty < (packageList[j].GoodsPieceQty - packageList[j].ReceiveGoodsPieceQty))
                            {
                                packageList[j].ReceiveGoodsPieceQty += iPieceQty;
                                iPieceQty = 0;
                            }
                            else if (iPieceQty == (packageList[j].GoodsPieceQty - packageList[j].ReceiveGoodsPieceQty))
                            {
                                packageList[j].ReceiveGoodsPieceQty += iPieceQty;
                                iPieceQty = 0;
                            }
                            else if (iPieceQty > (packageList[j].GoodsPieceQty - packageList[j].ReceiveGoodsPieceQty))
                            {
                                iPieceQty = iPieceQty - (packageList[j].GoodsPieceQty - packageList[j].ReceiveGoodsPieceQty);
                                packageList[j].ReceiveGoodsPieceQty = packageList[j].GoodsPieceQty;
                            }

                            //计算总数
                            packageList[j].ReceiveGoodsQty = packageList[j].ReceiveGoodsPackageQty * packageList[j].GoodsSpec
                                + packageList[j].ReceiveGoodsPieceQty;
                            if (!client.UpdateInPlanBillDetail(packageList[j]))
                            {
                                MessageBox.Show("更新入库计划明细信息失败！");
                                return;
                            }
                        }
                        else
                        {
                            if (j != (packageList.Count - 1))
                            {
                                continue;
                            }
                            else
                            {
                                packageList[j].ReceiveGoodsPackageQty += iPackageQty;
                                packageList[j].ReceiveGoodsPieceQty += iPieceQty;
                                packageList[j].ReceiveGoodsQty = packageList[j].ReceiveGoodsPackageQty * packageList[j].GoodsSpec
                               + packageList[j].ReceiveGoodsPieceQty;
                                if (!client.UpdateInPlanBillDetail(packageList[j]))
                                {
                                    MessageBox.Show("更新入库计划明细信息失败！");
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                //零数
                List<BilInPlanBillDetail> pieceList = _recieveList.Where(c => c.GoodsCode == sGoodsCode).ToList();
                if (pieceList.Count == 0)
                {
                    //计划之外
                }
                else if (pieceList.Count == 1)
                {
                    bHave = true;
                    pieceList[0].ReceiveGoodsPackageQty += iPackageQty;
                    pieceList[0].ReceiveGoodsPieceQty += iPieceQty;
                    pieceList[0].ReceiveGoodsQty = pieceList[0].ReceiveGoodsPackageQty * pieceList[0].GoodsSpec + pieceList[0].ReceiveGoodsPieceQty;

                    if (!client.UpdateInPlanBillDetail(pieceList[0]))
                    {
                        MessageBox.Show("更新出库计划明细信息失败！");
                        return;
                    }
                }
                else if (pieceList.Count > 1)
                {
                    bHave = true;
                    for (int j = 0; j < pieceList.Count; j++)
                    {
                        if (pieceList[j].ReceiveGoodsPackageQty < pieceList[j].GoodsPackageQty ||
                            pieceList[j].ReceiveGoodsPieceQty < pieceList[j].GoodsPieceQty)
                        {
                            if (iPackageQty < (pieceList[j].GoodsPackageQty - pieceList[j].ReceiveGoodsPackageQty))
                            {
                                pieceList[j].ReceiveGoodsPackageQty += iPackageQty;
                                iPackageQty = 0;
                            }
                            else if (iPackageQty == (pieceList[j].GoodsPackageQty - pieceList[j].ReceiveGoodsPackageQty))
                            {
                                pieceList[j].ReceiveGoodsPackageQty += iPackageQty;
                                iPackageQty = 0;
                            }
                            else if (iPackageQty > (pieceList[j].GoodsPackageQty - pieceList[j].ReceiveGoodsPackageQty))
                            {
                                iPackageQty = iPackageQty - (pieceList[j].GoodsPackageQty - pieceList[j].ReceiveGoodsPackageQty);
                                pieceList[j].ReceiveGoodsPackageQty = pieceList[j].GoodsPackageQty;
                            }

                            if (iPieceQty < (pieceList[j].GoodsPieceQty - pieceList[j].ReceiveGoodsPieceQty))
                            {
                                pieceList[j].ReceiveGoodsPieceQty += iPieceQty;
                                iPieceQty = 0;
                            }
                            else if (iPieceQty == (pieceList[j].GoodsPieceQty - pieceList[j].ReceiveGoodsPieceQty))
                            {
                                pieceList[j].ReceiveGoodsPieceQty += iPieceQty;
                                iPieceQty = 0;
                            }
                            else if (iPieceQty > (pieceList[j].GoodsPieceQty - pieceList[j].ReceiveGoodsPieceQty))
                            {
                                iPieceQty = iPieceQty - (pieceList[j].GoodsPieceQty - pieceList[j].ReceiveGoodsPieceQty);
                                pieceList[j].ReceiveGoodsPieceQty = pieceList[j].GoodsPieceQty;
                            }

                            //
                            pieceList[j].ReceiveGoodsQty = pieceList[j].ReceiveGoodsPackageQty * pieceList[j].GoodsSpec
                                + pieceList[j].ReceiveGoodsPieceQty;

                            if (!client.UpdateInPlanBillDetail(pieceList[j]))
                            {
                                MessageBox.Show("更新入库计划明细信息失败！");
                                return;
                            }
                        }
                        else
                        {
                            if (j != (pieceList.Count - 1))
                            {
                                continue;
                            }
                            else
                            {
                                pieceList[j].ReceiveGoodsPackageQty += iPackageQty;
                                pieceList[j].ReceiveGoodsPieceQty += iPieceQty;
                                pieceList[j].ReceiveGoodsQty = pieceList[j].ReceiveGoodsPackageQty * pieceList[j].GoodsSpec
                                        + pieceList[j].ReceiveGoodsPieceQty;
                                if (!client.UpdateInPlanBillDetail(pieceList[j]))
                                {
                                    MessageBox.Show("更新入库计划明细信息失败！");
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            if (!bHave)
            {
                if (MessageBox.Show("收货计划中无此项商品的记录，是否添加？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }
                ServiceReferenceZwms.ServiceZwmsClient client1
                     = new ServiceReferenceZwms.ServiceZwmsClient();
                BaseGood queryRecord = new BaseGood();
                queryRecord.Id = sGoodsCode;
                PagerIndex pagerIndex = new PagerIndex(1, int.MaxValue);
                queryRecord = client1.QueryGoods(queryRecord);

                if (queryRecord == null)
                {
                    MessageBox.Show("获取货物信息失败！");
                    return;
                }

                BilInPlanBillDetail record = new BilInPlanBillDetail();
                record.IBPlanCode = _sInPlanBillCode;
                record.GoodsBarCode = queryRecord.SingleGoodsCode;
                record.GoodsCode = sGoodsCode;
                record.GoodsName = queryRecord.GoodsName;
                record.GoodsSpec = queryRecord.Specs;
                record.SingleGoodsCode = queryRecord.SingleGoodsCode;
                if (!client.AddInPlanBillDetail(record))
                {
                    MessageBox.Show("添加入库计划信息失败！");
                    return;
                }
            }
            LoadPlanRecieveList();
        }

        //从扫描的条码中获取货物条码  格式“货物条码#入库时间”
        private string GetGoodsCode(string sScanBarCode,ref string sDate)
        {
            if (sScanBarCode.Contains('#'))
            {
                List<string> sList = CommonHelper.splitStr(sScanBarCode, '#');
                if (sList.Count != 2)
                {
                    return null;
                }
                else
                {
                    sDate = sList[1];
                    return sList[0];
                }
            }
            else
            {
                foreach (BilInPlanBillDetail record in _recieveList)
                {
                    if (record.SingleGoodsCode == sScanBarCode)
                    {
                        return record.GoodsCode;
                    }
                }


                ServiceReferenceZwms.ServiceZwmsClient client
                    = new ServiceReferenceZwms.ServiceZwmsClient();
                BaseGood queryRecord = new BaseGood();
                queryRecord.SingleGoodsCode = sScanBarCode;
                PagerIndex pagerIndex = new PagerIndex(1, int.MaxValue);
                IList<BaseGood> goodsList = client.QueryGoodsList(queryRecord, ref  pagerIndex);
                if (goodsList.Count > 0)
                {
                    return goodsList[0].Id;
                }
                else
                {
                    return null;
                }
            }
        }

        private void ResetNud()
        {
            nudPackageQty.Value = 0;
            nudPieceQty.Value = 0;
        }
        #endregion

        #region 控件函数
        private void tbBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 按下回车键
            if (e.KeyChar == '\r')
            {
                if (chbAutoSave.Checked)
                {
                    //当自动保存被选中，此时回车键为将结果自动添加
                    string sDate = "";
                    string sGoodsCode = GetGoodsCode(tbBarCode.Text,ref sDate);
                    if (tbBarCode.Text.Contains("#"))
                    {
                        RecieveGoods(sGoodsCode,sDate, 1, 0);
                    }
                    else
                    {
                        RecieveGoods(sGoodsCode,sDate, 0, 1);
                    }
                   
                }
                else
                {
                    //调整数量
                    if (_sLastScanCode == tbBarCode.Text)
                    {
                        if (tbBarCode.Text.Contains("#"))
                        {
                            nudPackageQty.Value += 1;
                        }
                        else
                        {
                            nudPieceQty.Value += 1;
                        }
                    }
                    else
                    {
                        if (tbBarCode.Text.Contains("#"))
                        {
                            nudPackageQty.Enabled = true;
                            nudPackageQty.Value = 1;
                        }
                        else
                        {
                            nudPackageQty.Enabled = false;
                            nudPackageQty.Value = 0;
                            nudPieceQty.Value = 1;
                        }
                    }
                    _sLastScanCode = tbBarCode.Text;
                }
                e.Handled = true;
                tbBarCode.SelectAll();
            }
        }

        private void nudQty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
               
                if (!chbAutoSave.Checked)
                {
                    try
                    {
                        string sDate = "";
                        string sGoodsCode = GetGoodsCode(tbBarCode.Text, ref sDate);
                        RecieveGoods(sGoodsCode, sDate, Convert.ToInt32(nudPackageQty.Value), Convert.ToInt32(nudPieceQty.Value));
                        ResetNud();
                    }
                    catch
                    {
                        ResetNud();
                    }
                }
            }
        }

        private void chbAutoSave_CheckedChanged(object sender, EventArgs e)
        {
            nudPackageQty.Enabled = !chbAutoSave.Checked;
            nudPieceQty.Enabled = !chbAutoSave.Checked;
            tbBarCode.Text = string.Empty;
            if (chbAutoSave.Checked)
            {
                nudPackageQty.Value = 0;
                nudPieceQty.Value = 0;
            }
        }

        private void btnClearSingle_Click(object sender, EventArgs e)
        {
            if (lsvPlanRecieve.SelectedItems.Count > 0)
            {
                ListViewItem selectItem = lsvPlanRecieve.SelectedItems[0];


                ServiceReferenceZwms.ServiceZwmsClient client
                  = new ServiceReferenceZwms.ServiceZwmsClient();
                foreach (BilInPlanBillDetail record in _recieveList)
                {
                    if (selectItem.Text == record.GoodsBarCode)
                    {
                        record.ReceiveGoodsPackageQty = 0;
                        record.ReceiveGoodsPieceQty = 0;
                        record.ReceiveGoodsQty = 0;

                        if (!client.UpdateInPlanBillDetail(record))
                        {
                            MessageBox.Show("更新入库计划明细信息失败！");
                            return;
                        }
                        break;
                    }
                }
                LoadPlanRecieveList();
            }
            else
            {
                MessageBox.Show("请首先选择要清空的收货记录！");
                return;
            }
        }

        private void btnEditSingle_Click(object sender, EventArgs e)
        {
            if (lsvPlanRecieve.SelectedItems.Count > 0)
            {
                ListViewItem selectItem = lsvPlanRecieve.SelectedItems[0];
                LoadPlanRecieveList();
            }
            else
            {
                MessageBox.Show("请首先选择要编辑的收货记录！");
                return;
            }
        }

        private void btnClearAll_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("清空全部收货信息，是否继续？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }
            ServiceReferenceZwms.ServiceZwmsClient client
                = new ServiceReferenceZwms.ServiceZwmsClient();

            foreach (BilInPlanBillDetail record in _recieveList)
            {
                record.ReceiveGoodsPackageQty = 0;
                record.ReceiveGoodsPieceQty = 0;
                record.ReceiveGoodsQty = 0;

                if (!client.UpdateInPlanBillDetail(record))
                {
                    MessageBox.Show("更新入库计划明细信息失败！");
                    return;
                }
            }
            LoadPlanRecieveList();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("完成收货？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            //1.入库单状态改为正在“正在上架”
            //2.将入库计划单中的收货信息同步到入库单中


            ServiceReferenceZwms.ServiceZwmsClient client
                = new ServiceReferenceZwms.ServiceZwmsClient();
            {
                BilInPlanBill queryRecord = new BilInPlanBill();
                queryRecord.Id = _sInPlanBillCode;
                queryRecord = client.QueryInPlanBill(queryRecord);
                queryRecord.BillStatus = "2";//收货完成
                if (!client.UpdateInPlanBill(queryRecord))
                {
                    MessageBox.Show("更新入库计划单失败！");
                    return;
                }
            }
            {
                BilInBill queryRecord = new BilInBill();
                queryRecord.Id = _sInBillCode;
                queryRecord = client.QueryInBill(queryRecord);
                queryRecord.BillStatus = "1"; //正在上架
                ServiceReferenceZwms.ServiceZwmsClient client1 = new ServiceReferenceZwms.ServiceZwmsClient();
                DateTime dtNow = client1.GetCurrentSystemTime();
                queryRecord.ReceiveDate = CommonHelper.GetDateString(dtNow);
                queryRecord.ReceiveTime = CommonHelper.GetTimeString(dtNow);
                if (client.UpdateInBill(queryRecord))
                {
                    SysLogWriter.WriteOptLog("收货完成更新", queryRecord.Id, "改");
                    List<BilInBillDetail> inBillList = new List<BilInBillDetail>();
                    foreach (BilInPlanBillDetail record in _recieveList)
                    {
                        if (record.ReceiveGoodsPackageQty == 0 &&
                           record.ReceiveGoodsPieceQty == 0 &&
                           record.GoodsPackageQty == 0 &&
                           record.GoodsPieceQty == 0)
                        {
                            continue;
                        }
                        BilInBillDetail ibd = new BilInBillDetail();
                        ibd.IBCode = this._sInBillCode;
                        ibd.GoodsCode = record.GoodsCode;
                        ibd.SingleGoodsCode = record.SingleGoodsCode;
                        ibd.GoodsBarCode = record.GoodsBarCode;
                        ibd.GoodsName = record.GoodsName;
                        ibd.GoodsSpec = record.GoodsSpec;
                        ibd.PiecePrice = record.PiecePrice;
                        ibd.GoodsPackageQty = record.GoodsPackageQty;
                        ibd.GoodsPieceQty = record.GoodsPieceQty;
                        ibd.GoodsQty = record.GoodsQty;
                        ibd.ReceiveGoodsPackageQty = record.ReceiveGoodsPackageQty;
                        ibd.ReceiveGoodsPieceQty = record.ReceiveGoodsPieceQty;
                        ibd.ReceiveGoodsQty = record.ReceiveGoodsQty;

                        inBillList.Add(ibd);
                       
                    }
                    if (!client.AddInBillDetailList(inBillList.ToArray()))
                    {
                        MessageBox.Show("添加入库单明细失败！");
                        return;
                    }

                    MessageBox.Show("收货完成！");
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show("更新入库单失败！");
                    return;
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void nudQty_Enter(object sender, EventArgs e)
        {
            NumericUpDown nud = sender as NumericUpDown;
            nud.Select(0, nud.Value.ToString().Length);
        }
        #endregion

      
    }
}
